using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Runtime.Serialization;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Code5Systems.ClientFramework;
using Code5Systems.FormMaster.Business;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security.Membership;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Mail;
using Microsoft.VisualBasic;

namespace Code5Systems.FormMaster
{

	public partial class FormMaster : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		//Implements Entities.Modules.IActionable
		//Implements Entities.Modules.IPortable
		
		
		private string ReplaceTokens(XDocument resultsDoc, string text)
		{
			string strAnswer = default(string);
			//Dim oAnswerNode As XmlNode
			XElement xAnswer = default(XElement);
			IEnumerable<XElement> xAnswers = default(IEnumerable<XElement>);
			XElement xARToken = default(XElement);
			
			System.Collections.Generic.List<XElement> xAnswerss = resultsDoc.Descendants("Answers").ToList();
			
			
			
			for (int i = 0; i <= xAnswerss.Count() - 1; i++)
			{
				strAnswer = "";
				xARToken = xAnswerss[i].Element("ARToken");
				if (xARToken != null)
				{
					if (xARToken.Value != string.Empty)
					{
						xAnswers = xAnswerss[i].Elements("Answer");
						
						foreach (XElement tempLoopVar_xAnswer in xAnswers)
						{
							xAnswer = tempLoopVar_xAnswer;
							strAnswer += xAnswer.Value + ", ";
						}
						
						if (strAnswer.Length > 0)
						{
							strAnswer = strAnswer.Substring(0, strAnswer.Length - 2);
						}
						
						text = text.Replace(xARToken.Value, strAnswer);
					}
				}
			}
			
			return text;
			
		}
		
		private void DoSilentPost(string payload)
		{
			WebResponse result = null;
			StringBuilder sb = new StringBuilder();
			string filePath = string.Empty;
			
			try
			{
				
				WebRequest req = default(WebRequest);
				Stream RequestStream = default(Stream);
				Stream ReceiveStream = default(Stream);
				Encoding encode = default(Encoding);
				StreamReader sr = default(StreamReader);
				
				req = WebRequest.Create(_objFormSettings.SilentPostUrl);
				req.Method = "POST";
				req.ContentType = "application/x-www-form-urlencoded";
				req.Timeout = 200000;
				byte[] SomeBytes = null;
				StringBuilder UrlEncoded = new StringBuilder();
				char[] reserved = new char[] {Strings.ChrW(63), Strings.ChrW(61), Strings.ChrW(38)};
				
				Utility.DoLogging(this.PortalId, this.ModuleId, string.Format("Opening Request To: {0}", _objFormSettings.SilentPostUrl), base.ModuleContext);
				if (payload != null)
				{
					SomeBytes = System.Text.Encoding.UTF8.GetBytes(payload);
					req.ContentLength = SomeBytes.Length;
					RequestStream = req.GetRequestStream();
					RequestStream.Write(SomeBytes, 0, SomeBytes.Length);
					RequestStream.Close();
				}
				else
				{
					req.ContentLength = 0;
				}
				
				Utility.DoLogging(this.PortalId, this.ModuleId, string.Format("Getting Response From: {0}", _objFormSettings.SilentPostUrl), base.ModuleContext);
				result = req.GetResponse();
				ReceiveStream = result.GetResponseStream();
				encode = System.Text.Encoding.GetEncoding("utf-8");
				sr = new StreamReader(ReceiveStream, encode);
				string strResponse = sr.ReadToEnd();
				sr.Close();
				
				Utility.DoLogging(this.PortalId, this.ModuleId, strResponse, base.ModuleContext);
				
			}
			catch (Exception Exc)
			{
				DotNetNuke.Services.Exceptions.Exceptions.LogException(Exc);
				sb.Append(Exc.Message);
				Utility.DoLogging(this.PortalId, this.ModuleId, Exc.Message, base.ModuleContext);
			}
			finally
			{
				if (result != null)
				{
					result.Close();
				}
			}
			
		}
		
		//Does the Redirection after Form Submission or if the user has already filled out the Survey
		private void DoRedirect()
		{
			string strParams = "";
			string strPostParams = "";
			string strUrl = "";
			bool isAjaxPostback = false;
			
			if (DotNetNuke.Framework.AJAX.IsEnabled())
			{
				isAjaxPostback = DotNetNuke.Framework.AJAX.GetScriptManager(this.Page).IsInAsyncPostBack;
			}
			
			if (_objResultsXmlDoc != null)
			{
				//Dim qParamsNode As XmlNode = objResultsXmlDoc.SelectSingleNode("//QParams")
				XElement xParams = _objResultsXmlDoc.Root.Element("QParams");
				
				if (xParams != null)
				{
					strParams = xParams.Value;
				}
				
				//Dim postParamsNode As XmlNode = objResultsXmlDoc.SelectSingleNode("//PostParams")
				XElement xPostParams = _objResultsXmlDoc.Root.Element("PostParams");
				
				if (xPostParams != null)
				{
					
					if (_objFormSettings.SilentPostUrl != string.Empty)
					{
						
						strPostParams = xPostParams.Value;
						
						if (strPostParams.StartsWith("&"))
						{
							strPostParams = strPostParams.Remove(0, 1);
						}
						
						DoSilentPost(strPostParams);
						
					}
				}
			}
			
			switch (_objFormSettings.RedirectType)
			{
				case "N":
					try
					{
						strUrl = DotNetNuke.Common.Globals.NavigateURL(TabId, "", "sbmt=1", "fmmid=" + ModuleId, "fdid=" + _formDataId.ToString());
						if (isAjaxPostback)
						{
							this.ShowThankYouPage();
							//Response.StatusCode = 201
							//Response.AddHeader("Location", strUrl)
						}
						else
						{
							Response.Redirect(strUrl);
						}
					}
					catch
					{
					}
					break;
					
				case "U":
					strUrl = _objFormSettings.RedirectUrl;
					if (strUrl.Contains("?"))
					{
						strUrl += strParams;
					}
					else if (strParams != string.Empty)
					{
						if (strParams.StartsWith("&"))
						{
							strParams = strParams.Remove(0, 1);
						}
						strUrl += "?" + strParams;
					}
					try
					{
						if (isAjaxPostback)
						{
							Response.StatusCode = 201;
							Response.AddHeader("Location", strUrl);
						}
						else
						{
							Response.Redirect(strUrl);
						}
						//DoAjaxRedirect(strUrl)
						//Response.Redirect(strUrl)
					}
					catch
					{
					}
					break;
				case "T":
					if (strParams.StartsWith("&"))
					{
						strParams = strParams.Remove(0, 1);
					}
					try
					{
						strUrl = DotNetNuke.Common.Globals.NavigateURL(int.Parse(_objFormSettings.RedirectUrl), "", strParams.Split('&'));
						if (isAjaxPostback)
						{
							Response.StatusCode = 201;
							Response.AddHeader("Location", strUrl);
						}
						else
						{
							Response.Redirect(strUrl);
						}
						
						//DoAjaxRedirect(NavigateURL(CInt(_objFormSettings.RedirectUrl), "", strParams.Split("&"c)))
						//Response.Redirect(NavigateURL(CInt(objFormSettings.RedirectUrl), "", strParams.Split("&"c)))
					}
					catch
					{
					}
					break;
				case "F":
					//Use the default option the file will download after the thank you
					//message has been shown
					try
					{
						strUrl = DotNetNuke.Common.Globals.NavigateURL(TabId, "", "sbmt=1", "fmmid=" + ModuleId, "fdid=" + _formDataId.ToString());
						if (isAjaxPostback)
						{
							this.ShowThankYouPage();
							//Response.StatusCode = 201
							//Response.AddHeader("Location", strUrl)
						}
						else
						{
							Response.Redirect(strUrl);
						}
						//DoAjaxRedirect(NavigateURL(TabId, "", "sbmt=1", "fmmid=" & ModuleId, "fdid=" & _formDataId))
						//Response.Redirect(NavigateURL(TabId, "", "sbmt=1", "fmmid=" & ModuleId, "fdid=" & formDataId))
					}
					catch
					{
					}
					break;
				default:
					//Default in case there is a a problem
					try
					{
						strUrl = DotNetNuke.Common.Globals.NavigateURL(TabId, "", "sbmt=1");
						if (isAjaxPostback)
						{
							Response.StatusCode = 201;
							Response.AddHeader("Location", strUrl);
						}
						else
						{
							Response.Redirect(strUrl);
						}
						//DoAjaxRedirect(NavigateURL(TabId, "", "sbmt=1"))
						//Response.Redirect(NavigateURL(TabId, "", "sbmt=1"))
					}
					catch
					{
					}
					break;
			}
			
			
		}
		
		private void ShowThankYouPage()
		{
			this.pnlForm.Visible = false;
			this.pnlThankYou.Visible = true;
			
			//Get the Thank You message
			XDocument xThankYouDoc = XDocument.Parse(_objFormInfo.FormDefinition);
			XElement xThankYou = default(XElement);
			xThankYou = xThankYouDoc.Root.Element("ThankYou");
			
			if (xThankYou != null)
			{
				if (xThankYou.Value != string.Empty)
				{
					string strContent = Server.HtmlDecode(xThankYou.Value);
					
					//Replace the Tokens
					if (_formDataId > Null.NullInteger)
					{
						Code5Systems.FormMaster.Business.FormDataController objFormDataCtl = new Code5Systems.FormMaster.Business.FormDataController();
						Code5Systems.FormMaster.Business.FormDataInfo objFormDataInfo = objFormDataCtl.Get(_formDataId, ModuleId);
						if (objFormDataInfo != null)
						{
							XDocument resultsDoc = new XDocument();
							resultsDoc = XDocument.Parse(objFormDataInfo.FormData);
							strContent = this.ReplaceTokens(resultsDoc, strContent);
						}
					}
					
					this.lblThankYou.Text = strContent;
					
				}
			}
			
			//If the Redirect Rule is set to File, Create an IFRAME set the src
			//attribute to the URL of the file and set hlDownload NavigateUrl property
			//in case the users browser does not allow automatic downloads
			if (_objFormSettings.RedirectType == "F")
			{
				int intVal;
				int.TryParse(this._objFormSettings.RedirectUrl, out intVal);
				DotNetNuke.Services.FileSystem.FileInfo oFileInfo = FileManager.Instance.GetFile(intVal) as DotNetNuke.Services.FileSystem.FileInfo;

				if (oFileInfo != null)
				{
					StringBuilder FrameText = new StringBuilder();
					
					this.hlDownload.Text = Localization.GetString("DownloadFile", this.LocalResourceFile) + " " + oFileInfo.FileName;
					this.hlDownload.NavigateUrl = PortalSettings.HomeDirectory + oFileInfo.Folder + oFileInfo.FileName;
					this.hlDownload.Visible = true;
					
					FrameText.Append("<iframe frameborder=\"0\"");
					FrameText.Append("\" src=\"");
					FrameText.Append(PortalSettings.HomeDirectory + oFileInfo.Folder + oFileInfo.FileName);
					FrameText.Append("\" height=\"1\" width=\"1\" title=\"Download\" name=\"Download\" scrolling=\"no\"");
					FrameText.Append("\">");
					FrameText.Append("</iframe>");
					lblIFrame.Text = FrameText.ToString();
					
				}
			}
		}
		
		private void SendAutoResponder(XDocument resultsDoc)
		{
			string SMTPServer = string.Empty;
			string SMTPAuthentication = string.Empty;
			string SMTPUsername = string.Empty;
			string SMTPPassword = string.Empty;
			bool SMTPEnableSSL = Null.NullBoolean;
			string strBody = string.Empty;
			string strSendTo = default(string);
			string strSendFrom = default(string);
			
			try
			{
				strSendTo = GetEmailAutoResponseAddress();
				
				if (string.IsNullOrEmpty(strSendTo))
				{
					return ;
				}

				if (!String.IsNullOrWhiteSpace(Host.SMTPServer))
				{
					SMTPServer = Host.SMTPServer;
				}

				if (!String.IsNullOrWhiteSpace(Host.SMTPAuthentication))
				{
					SMTPAuthentication = Host.SMTPAuthentication;
				}

				if (!String.IsNullOrWhiteSpace(Host.SMTPUsername))
				{
					SMTPUsername = Host.SMTPUsername;
				}

				if (!String.IsNullOrWhiteSpace(Host.SMTPPassword))
				{
					SMTPPassword = Host.SMTPPassword;
				}

				SMTPEnableSSL = Host.EnableSMTPSSL;
				
				if (_objFormSettings.AutoRespFromEmail != string.Empty)
				{
					strSendFrom = _objFormSettings.AutoRespFromEmail;
				}
				else if (Utility.ValidateEmailAddressFormat(this.PortalSettings.Email))
				{
					strSendFrom = this.PortalSettings.PortalName.Replace(",", "") + "<" + this.PortalSettings.Email + ">";
				}
				else
				{
					strSendFrom = System.Convert.ToString(DotNetNuke.Entities.Controllers.HostController.Instance.GetSettingsDictionary()["HostEmail"]);
				}
				
				Encoding encod = GetEncoding();
				
				System.Net.Mail.MailMessage objMail = new System.Net.Mail.MailMessage(strSendFrom, strSendTo);
				
				objMail.SubjectEncoding = encod;
				objMail.BodyEncoding = encod;
				
				objMail.IsBodyHtml = true;
				
				objMail.Subject = _objFormSettings.AutoRespSubject;
				
				// external SMTP server
				int SmtpPort = Null.NullInteger;
				int portPos = SMTPServer.IndexOf(":");
				if (portPos > -1)
				{
					SmtpPort = int.Parse(SMTPServer.Substring(portPos + 1, SMTPServer.Length - portPos - 1));
				}
				
				System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
				
				if (SMTPServer != "")
				{
					
					//Port Code Fix Submitted by Brad Murray - Thanks Brad
					if (SmtpPort > Null.NullInteger)
					{
						smtpClient.Host = SMTPServer.Replace(":" + SmtpPort.ToString(), "");
						smtpClient.Port = SmtpPort;
					}
					else
					{
						smtpClient.Host = SMTPServer;
					}
					
					switch (SMTPAuthentication)
					{
						case "": // anonymous
						case "0":
							break;
						case "1": // basic
							if (SMTPUsername != "" && SMTPPassword != "")
							{
								smtpClient.Credentials = new System.Net.NetworkCredential(SMTPUsername, SMTPPassword);
							}
							break;
						case "2": // NTLM
							smtpClient.UseDefaultCredentials = true;
							break;
					}
				}
				
				smtpClient.EnableSsl = SMTPEnableSSL;
				
				XDocument xDoc = XDocument.Parse(_objFormCtl.FormInfo.FormDefinition);
				XElement xAutoResp = default(XElement);
				
				//Find the AutoResponse Element and set the editor control text property
				xAutoResp = xDoc.Root.Element("AutoResponse");
				if (xAutoResp != null)
				{
					strBody = Server.HtmlDecode(System.Convert.ToString(xAutoResp.Value));
				}
				
				strBody = ReplaceTokens(resultsDoc, strBody);
				
				objMail.Body = strBody;
				
				MemoryStream memStream = default(MemoryStream);
				
				if (_objFormSettings.ARAttachment != string.Empty)
				{
					FileController oFileCtl = new FileController();
					DotNetNuke.Services.FileSystem.FileInfo oFileInfo = default(DotNetNuke.Services.FileSystem.FileInfo);
					oFileInfo = oFileCtl.GetFileById(int.Parse(_objFormSettings.ARAttachment), PortalId);
					
					byte[] fileBytes = null;
					
					if (oFileInfo != null)
					{
						if (oFileInfo.StorageLocation == 0)
						{
							
							if (File.Exists(Server.MapPath("Portals/" + PortalId + "/" + oFileInfo.Folder + oFileInfo.FileName)))
							{
								fileBytes = File.ReadAllBytes(Server.MapPath("Portals/" + PortalId + "/" + oFileInfo.Folder + oFileInfo.FileName));
							}
							
						}
						else if (oFileInfo.StorageLocation == 1)
						{
							if (File.Exists(Server.MapPath("Portals/" + PortalId + "/" + oFileInfo.Folder + oFileInfo.FileName + ".resources")))
							{
								fileBytes = File.ReadAllBytes(Server.MapPath("Portals/" + PortalId + "/" + oFileInfo.Folder + oFileInfo.FileName + ".resources"));
							}
							
						}
						else
						{
							fileBytes = oFileCtl.GetFileContent(oFileInfo.FileId, PortalId);
						}
						
						if (fileBytes != null)
						{
							memStream = new MemoryStream(fileBytes);
							objMail.Attachments.Add(new Attachment(memStream, oFileInfo.FileName, oFileInfo.ContentType));
						}
						
					}
				}
				
				smtpClient.Send(objMail);
				
				// Close all Open File Attachment Streams
				foreach (Attachment attachment in objMail.Attachments)
				{
					attachment.ContentStream.Close();
				}
				
			}
			catch (HttpException exHttp)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exHttp.GetBaseException().Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				Exceptions.LogException(exHttp);
			}
			catch (Exception exc)
			{
				DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, exc.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
				Exceptions.LogException(exc);
			}
			
		}
		
		private string GetFieldValue(string field)
		{
			Code5Systems.FormMaster.Business.FormControlInfo oFormControlInfo = default(Code5Systems.FormMaster.Business.FormControlInfo);
			string strFieldValue = string.Empty;
			Control oControl = default(Control);
			oControl = (Control) (this.FindControl(field));
			
			if (oControl != null)
			{
				oFormControlInfo = this._objFormCtl.GetFormControlInfo(this._objFormInfo, oControl.ID);
				
				switch (oControl.GetType().ToString())
				{
					case "System.Web.UI.WebControls.DropDownList":
						strFieldValue = ((System.Web.UI.WebControls.DropDownList) oControl).SelectedValue;
						
						if (oFormControlInfo.EncryptField)
						{
							strFieldValue = Utility.DecryptString(strFieldValue);
						}
						break;
						
					case "System.Web.UI.WebControls.RadioButtonList":
						strFieldValue = ((System.Web.UI.WebControls.RadioButtonList) oControl).SelectedValue;
						
						if (oFormControlInfo.EncryptField)
						{
							strFieldValue = Utility.DecryptString(strFieldValue);
						}
						break;
						
					case "System.Web.UI.WebControls.TextBox":
						strFieldValue = ((System.Web.UI.WebControls.TextBox) oControl).Text;
						
						if (oFormControlInfo.EncryptField)
						{
							strFieldValue = Utility.DecryptString(strFieldValue);
						}
						break;
						
					case "System.Web.UI.WebControls.ListBox":
						ListBox oListBox = (ListBox) oControl;
						ListItem oListItem_1 = default(ListItem);
						foreach (ListItem tempLoopVar_oListItem_1 in oListBox.Items)
						{
							oListItem_1 = tempLoopVar_oListItem_1;
							if (oListItem_1.Selected)
							{
								
								if (oFormControlInfo.EncryptField)
								{
									oListItem_1.Value = Utility.DecryptString(oListItem_1.Value);
								}
								
								if (strFieldValue.IndexOf(oListItem_1.Value) == -1)
								{
									if (!strFieldValue.Contains(oListItem_1.Value))
									{
										strFieldValue += oListItem_1.Value + ";";
									}
								}
							}
						}
						
						strFieldValue = strFieldValue.Substring(0, strFieldValue.Length - 1);
						break;
						
					case "System.Web.UI.WebControls.CheckBoxList":
						CheckBoxList oCheckBoxList = (CheckBoxList) oControl;
						ListItem oListItem = default(ListItem);
						foreach (ListItem tempLoopVar_oListItem in oCheckBoxList.Items)
						{
							oListItem = tempLoopVar_oListItem;
							if (oListItem.Selected)
							{
								
								if (oFormControlInfo.EncryptField)
								{
									oListItem.Value = Utility.DecryptString(oListItem.Value);
								}
								
								if (strFieldValue.IndexOf(oListItem.Value) == -1)
								{
									if (!strFieldValue.Contains(oListItem.Value))
									{
										strFieldValue += oListItem.Value + ";";
									}
								}
							}
						}
						
						strFieldValue = strFieldValue.Substring(0, strFieldValue.Length - 1);
						break;
						
					case "System.Web.UI.WebControls.HiddenField":
						strFieldValue = ((System.Web.UI.WebControls.HiddenField) oControl).Value;
						
						if (oFormControlInfo.EncryptField)
						{
							strFieldValue = Utility.DecryptString(strFieldValue);
						}
						break;
				}
			}
			
			return strFieldValue;
		}
		
		private void DisableCommandControls(Control formControl)
		{
			foreach (Control ctrl in formControl.Controls)
			{
				if (true == (ctrl is LinkButton))
				{
					ctrl.Visible = false;
				}
				else if (true == (ctrl is Button))
				{
					ctrl.Visible = false;
				}
				else if (true == (ctrl is ImageButton))
				{
					ctrl.Visible = false;
				}
				if (ctrl.HasControls())
				{
					DisableCommandControls(ctrl);
				}
			}
		}
		
		private Encoding GetEncoding()
		{
			Encoding encod = default(Encoding);
			switch (_objFormSettings.Encoding)
			{
				case Code5Systems.FormMaster.Business.EmailEncoding.Default:
					encod = Encoding.GetEncoding(System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage);
					break;
				case Code5Systems.FormMaster.Business.EmailEncoding.UTF8:
					encod = Encoding.UTF8;
					break;
				case Code5Systems.FormMaster.Business.EmailEncoding.UTF7:
					encod = Encoding.UTF7;
					break;
				case Code5Systems.FormMaster.Business.EmailEncoding.Unicode:
					encod = Encoding.Unicode;
					break;
				case Code5Systems.FormMaster.Business.EmailEncoding.ASCII:
					encod = Encoding.ASCII;
					break;
				case Code5Systems.FormMaster.Business.EmailEncoding.UTF32:
					encod = Encoding.UTF32;
					break;
				case Code5Systems.FormMaster.Business.EmailEncoding.BigEndianUnicode:
					encod = Encoding.BigEndianUnicode;
					break;
				default:
					encod = Encoding.Default;
					break;
			}
			return encod;
		}
		
		public bool RegisterUser()
		{
			bool bSuccess = true;
			UserInfo objUser = null;
			UserLoginStatus loginStatus = UserLoginStatus.LOGIN_FAILURE;
			UserCreateStatus CreateStatus = UserCreateStatus.UnexpectedError;
			
			if (UserInfo.IsSuperUser || UserInfo.IsInRole("Administrators"))
			{
				return bSuccess;
			}
			
			if (_objFormSettings.RegisterUser)
			{
				if (!Context.User.Identity.IsAuthenticated)
				{
					
					//objUser = UserController.GetUserByName(PortalId, Me.GetFieldValue(objFormSettings.UserNameField))
					
					//If objUser Is Nothing Then
					objUser = new UserInfo();
					objUser.PortalID = PortalId;
					objUser.FirstName = this.GetFieldValue(_objFormSettings.FirstNameField);
					objUser.DisplayName = objUser.FirstName;
					objUser.LastName = this.GetFieldValue(_objFormSettings.LastNameField);
					objUser.Email = this.GetFieldValue(_objFormSettings.EmailField);
					objUser.Email = objUser.Email;
					objUser.Username = this.GetFieldValue(_objFormSettings.UserNameField);
					objUser.Username = objUser.Username;
					objUser.Membership.Password = this.GetFieldValue(_objFormSettings.PasswordField);
					objUser.AffiliateID = Null.NullInteger;
					
					if (PortalSettings.UserRegistration == (int) DotNetNuke.Common.Globals.PortalRegistrationType.PublicRegistration)
					{
						objUser.Membership.Approved = true;
					}
					else
					{
						objUser.Membership.Approved = false;
					}
					
					CreateStatus = UserController.CreateUser(ref objUser);
					
					if (CreateStatus == DotNetNuke.Security.Membership.UserCreateStatus.Success)
					{
						bSuccess = true;
						DataCache.ClearPortalCache(objUser.PortalID, false);
						
						// send notification to portal administrator of new user registration
						Mail.SendMail(objUser, MessageType.UserRegistrationAdmin, PortalSettings);
						
						switch (PortalSettings.UserRegistration)
						{
							case (System.Int32) DotNetNuke.Common.Globals.PortalRegistrationType.PrivateRegistration:
								Mail.SendMail(objUser, MessageType.UserRegistrationPrivate, PortalSettings);
								break;
								
							case (System.Int32) DotNetNuke.Common.Globals.PortalRegistrationType.PublicRegistration:
								Mail.SendMail(objUser, MessageType.UserRegistrationPublic, PortalSettings);
								UserController.UserLogin(PortalSettings.PortalId, objUser.Username, objUser.Membership.Password, "", PortalSettings.PortalName, "", ref loginStatus, false);
								break;
								
							case (System.Int32) DotNetNuke.Common.Globals.PortalRegistrationType.VerifiedRegistration:
								Mail.SendMail(objUser, MessageType.UserRegistrationVerified, PortalSettings);
								break;
								
						}
					}
					else
					{
						objUser = null;
						_postResult = Code5Systems.FormMaster.Business.FormPostResult.FailedRegistration;
						DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, Utility.GetRegistrationResponse(CreateStatus), DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
					}
				}
			}
			
			// If the user is logged in or has just been created then assign Roles
			if (Context.User.Identity.IsAuthenticated || CreateStatus == UserCreateStatus.Success)
			{
				if (objUser == null)
				{
					objUser = this.UserInfo;
				}
				_userId = objUser.UserID;
				DotNetNuke.Security.Roles.RoleInfo objRoleInfo = default(DotNetNuke.Security.Roles.RoleInfo);
				DotNetNuke.Security.Roles.RoleController objRoleController = new DotNetNuke.Security.Roles.RoleController();
				if (!string.IsNullOrEmpty(_objFormSettings.UserRoles))
				{
					foreach (string role in _objFormSettings.UserRoles.Split(','))
					{
						if (!DotNetNuke.Security.PortalSecurity.IsInRole(role))
						{
							objRoleInfo = objRoleController.GetRoleByName(PortalId, role);
							if (objRoleInfo != null)
							{
								objRoleController.AddUserRole(PortalId, objUser.UserID, objRoleInfo.RoleID, Null.NullDate);
							}
							
						}
					}
				}
				
			}
			
			return bSuccess;
		}
		
		private void DoAjaxRedirect(string redirectTo)
		{
			//Me.pnlForm.Visible = False
			//Me.pnlThankYou.Visible = False
			string script = string.Format("window.location.href = \'{0}\';", redirectTo);
			UpdatePanel upPanel = Utility.GetChildsRecursive(this.Page).OfType<UpdatePanel>().FirstOrDefault();
			
			ScriptManager.RegisterStartupScript(upPanel, this.GetType(), "RedirectTo", script, true);
		}
		
		private void AddCaptchaRow(Table oFormTable, WebControl cmdSubmitButton, int tableRow)
		{
			if (this._objFormInfo.UseCaptcha && !this._isMultiPage)
			{
				TableRow oRow = new TableRow();
				oRow.ID = "trC5SCaptcha";
				TableCell oControlCell = new TableCell();
				oControlCell.ID = "tdC5SCaptcha";
				oControlCell.ColumnSpan = System.Convert.ToInt32(_objFormInfo.CurrentPage.LabelPosition == 2 ? _objFormInfo.CurrentPage.TableColumns * 2 : _objFormInfo.CurrentPage.TableColumns);
				oControlCell.HorizontalAlign = HorizontalAlign.Center;
				oControlCell.Attributes.Add("style", "padding:5px;display:none;");
				oControlCell.Attributes.Add("class", "C5SCaptchaCell");
				oRow.Cells.Add(oControlCell);
				if (oFormTable != null)
				{
					oFormTable.Rows.AddAt(tableRow - 1, oRow);
				}
			}
		}

		public bool CheckReCaptcha()
		{
			bool isValid = true;
			string response = String.Empty;
			string gresponse = Request.Form["g-Recaptcha-Response"];
			string[] responses = gresponse.Split(',');
			
			foreach (string resp in responses)
			{
				response += resp;
			}

			if (string.IsNullOrEmpty(response))
			{
				_hdnWzrdStart.Value = (this._objFormCtl.Pages.Count() - 1).ToString();
				var UPPanel = this.Parent;

				//ScriptManager.RegisterStartupScript(this, this.GetType(), "CaptchaReload", "$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {grecaptcha.reset();});", true);

				//ScriptManager.RegisterStartupScript(this, this.GetType(), "CaptchaReload", "debugger; alert('Hello'); grecaptcha.reset();", true);
				//ScriptManager.RegisterClientScriptBlock(this.Parent, this.Parent.GetType(), "CaptchaReload", "debugger; alert('Hello'); grecaptcha.reset();", true);
				//Literal scrLit = new Literal();
				//scrLit.ID = "MyLiteralControl";
				//scrLit.Text = @"HELLO HELLO HELLO <script type=""text/javascript"">debugger; alert('Hello'); grecaptcha.reset();</script>";
				//pnlDynScripts.Controls.Add(scrLit);
				//pnlDynScripts.Visible = true;
				
				//Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "script", "alert('Success!');", true);
				//lblReCaptchaErrMsg.Text = Localization.GetString("CaptchaRequired", this.LocalResourceFile);
				//lblReCaptchaErrMsg.Visible = true;
				return false;
			}

			//lblCaptchaErrMsg.Visible = false;

			var client = new System.Net.WebClient();


			var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", _objFormSettings.SecretKey, response));

			var reCaptchaResponse = SerializationHelper.JsonDeserialize<ReCaptchaResponse>(googleReply);
			string errorMessage = string.Empty;
			if (!reCaptchaResponse.Success)
			{
				isValid = false;
				if (reCaptchaResponse.ErrorCodes.Any())
				{
					var error = reCaptchaResponse.ErrorCodes[0].ToLower();
					switch (error)
					{
						case ("missing-input-secret"):
							errorMessage = "The secret parameter is missing.";
							break;
						case ("invalid-input-secret"):
							errorMessage = "The secret parameter is invalid or malformed.";
							break;

						case ("missing-input-response"):
							errorMessage = "The response parameter is missing.";
							break;
						case ("invalid-input-response"):
							errorMessage = "The response parameter is invalid or malformed.";
							break;

						default:
							errorMessage = "Error occurred. Please try again";
							break;
					}
				}
				_hdnWzrdStart.Value = (this._objFormCtl.Pages.Count() - 1).ToString();
				//ScriptManager.RegisterStartupScript(this, this.GetType(), "CaptchaReload", "$.getScript(\"https://www.google.com/recaptcha/api.js\", function () {grecaptcha.reset();});", true);
				ScriptManager.RegisterStartupScript(this, this.GetType(), "CaptchaReload", "grecaptcha.reset();", true);
				//var oRowFluid = new HtmlGenericControl("div");
				//oRowFluid.Attributes.Add("class", "C5LLC_row-fluid");
				//oRowFluid.ID = "trC5SCaptcha";

				//var oControlDiv = new HtmlGenericControl("div");
				//oControlDiv.Attributes.Add("class", "g-recaptcha");
				//oControlDiv.Attributes.Add("data-sitekey", _objFormSettings.SiteKey);

				//oRowFluid.Controls.Add(oControlDiv);
				//oFormDiv.Controls.Add(oRowFluid);
				
			}

				//System.Version version = DotNetNuke.Application.DotNetNukeContext.Current.Application.Version;
				//if (version.Major >= 7)
				//{
				//	lblCaptchaErrMsg.CssClass = "dnnFormMessage dnnFormError";
				//}
				//else
				//{
				//	lblCaptchaErrMsg.CssClass = "NormalRed";
				//}

			return isValid;

		}
		
		public bool CheckCaptcha()
		{
			bool isValid = true;
			lblCaptchaErrMsg.Visible = false;

			if (_objFormInfo.UseCaptcha)
			{
				if (_objFormSettings.CaptchaType == CaptchaType.GoogleReCaptcha)
				{
					return CheckReCaptcha();
				}
				isValid = this.ctl_c5sllc_Captcha.IsValid;
				string captchaValue = string.Empty;
				//Dim myTB As IEnumerable(Of Control) = Utility.GetChildsRecursive(Me.ctl_c5sllc_Captcha).OfType(Of Control)().FirstOrDefault()
				foreach (string key in Request.Form.Keys)
				{
					if (key.EndsWith("ctl_c5sllc_Captcha"))
					{
						captchaValue = Request.Form[key];
						break;
					}
				}

				if (string.IsNullOrEmpty(captchaValue))
				{
					lblCaptchaErrMsg.Text = Localization.GetString("CaptchaRequired", this.LocalResourceFile);
					lblCaptchaErrMsg.Visible = true;
					_hdnWzrdStart.Value = (this._objFormCtl.Pages.Count() - 1).ToString();
				}
				else if (!isValid)
				{
					//lblCaptchaErrMsg.Text = Localization.GetString("CaptchaInvalid", this.LocalResourceFile);
					//lblCaptchaErrMsg.Visible = true;
					_hdnWzrdStart.Value = (this._objFormCtl.Pages.Count() - 1).ToString();
				}
				else
				{
					lblCaptchaErrMsg.Visible = false;
				}

				System.Version version = DotNetNuke.Application.DotNetNukeContext.Current.Application.Version;
				if (version.Major >= 7)
				{
					lblCaptchaErrMsg.CssClass = "dnnFormMessage dnnFormError";
				}
				else
				{
					lblCaptchaErrMsg.CssClass = "NormalRed";
				}
			}

			return isValid;
			
		}
		
	}

	[DataContract]
	public class ReCaptchaResponse
	{
		[DataMember(Name = "success")]
		public bool Success { get; set; }

		[DataMember(Name = "error-codes")]
		public string[] ErrorCodes { get; set; }
	}
	
}

